//
//  PictureBrowserViewController.swift
//  MicroBlog
//
//  Created by  NorthCity on 15/11/18.
//  Copyright © 2015年  NorthCity. All rights reserved.
//

import UIKit
import SVProgressHUD
//可重用 cell 标示
private let PictureBrowserCellID = "PictureBrowserCellID"
class PictureBrowserViewController: UIViewController {
    
//MARK: - 属性
//    url 数组
    var urls:[NSURL]
//    选中照片索引
    var selectedIndexPath:NSIndexPath
//MARK: -    构造函数
    init(urls:[NSURL],indexPath:NSIndexPath){
        self.urls = urls
        selectedIndexPath = indexPath
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func loadView() {
        var rect = UIScreen.mainScreen().bounds
        rect.size.width += 20
        view = UIView(frame: rect)
        setUpUI()
    }
    override func viewDidLoad() {
        collectionView.scrollToItemAtIndexPath(selectedIndexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
    }
    
//MARK -懒加载控件
    /// collectionView
    private lazy var collectionView:UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: pictureBrowserLayout())
    /// 关闭按钮
    private lazy var closeButton:UIButton = UIButton(
        title: "关闭",
        fontSize: 14,
        color: UIColor.whiteColor(),
        imageName: nil,
        backColor: UIColor.darkGrayColor())
    /// 保存按钮
    private lazy var saveButton:UIButton = UIButton(
        title: "保存",
        fontSize: 14,
        color: UIColor.whiteColor(),
        imageName: nil,
        backColor: UIColor.darkGrayColor())
   }
//MARK: - 设置界面
private extension PictureBrowserViewController{
    func setUpUI(){
//        1 添加控件
        view.addSubview(collectionView)
        view.addSubview(closeButton)
        view.addSubview(saveButton)
//        2 设置布局
        collectionView.frame = view.bounds
        
        closeButton.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left).offset(8)
            make.bottom.equalTo(view.snp_bottom).offset(-8)
            make.width.equalTo(100)
            make.height.equalTo(36)
        }
        
        saveButton.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(view.snp_right).offset(-28)
            make.bottom.equalTo(view.snp_bottom).offset(-8)
            make.width.equalTo(100)
            make.height.equalTo(36)
        }
//        3 添加监听方法
        closeButton.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)
        saveButton.addTarget(self, action: "save", forControlEvents: UIControlEvents.TouchUpInside)
//        4 准备控件
        prepareCollectionView()
    }
//MARK: - 按钮监听方法
  @objc private func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
  @objc private func save(){
//    1 取得图片
     let cell = collectionView.visibleCells().last as? PictureBrowserCell
    guard let image = cell!.imageView.image else{
      return
    }
//    2 保存到相册
    UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
    
    
    }
    @objc private func image(image:UIImage,didFinishSavingWithError error:NSError?,contextInfo:AnyObject?){
        let message = (error != nil ? "保存失败" : "保存成功")
        SVProgressHUD.showErrorWithStatus(message)
        
    }
    
   private func prepareCollectionView(){
//    1 准备数据源
    collectionView.dataSource = self
//    2 注册 cell
    collectionView.registerClass(PictureBrowserCell.self, forCellWithReuseIdentifier: PictureBrowserCellID)
    
    }

}
//MARK: - 实现数据源方法
extension PictureBrowserViewController:UICollectionViewDataSource{
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return urls.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
       let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureBrowserCellID, forIndexPath: indexPath) as! PictureBrowserCell
        print(urls)
        cell.imageURL = urls[indexPath.item]
        cell.pictureCellDelegate = self
        return cell
    }
    
}
//MARK: - 实现自定义协议方法
extension PictureBrowserViewController:PictureBrowserCellDelegate{
    func pictureBrowserCellDidClickImage(){
        close()
    }
}
//Mark: - 设置 collectionView的布局
private class pictureBrowserLayout:UICollectionViewFlowLayout{
    private override func prepareLayout() {
        super.prepareLayout()
        itemSize = collectionView!.bounds.size
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        scrollDirection = .Horizontal
        
        
        collectionView?.pagingEnabled = true
        collectionView?.bounces = false
        collectionView?.showsHorizontalScrollIndicator = false
        
    }
}

//MARK: - 实现协议
extension PictureBrowserViewController:PictureBrowserDismissDelegate{
    
    func imageViewForDismiss() -> UIImageView {
        let iv = UIImageView()
        iv.contentMode = .ScaleAspectFill
        iv.clipsToBounds = true
        
        let cell = collectionView.visibleCells()[0] as! PictureBrowserCell
        iv.image = cell.imageView.image
        iv.frame = cell.scrollView.convertRect(cell.imageView.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        return iv
    }
    
    func indexPathForDismiss() -> NSIndexPath {
        return collectionView.indexPathsForVisibleItems()[0]
    }
    
}






